package com.yx1996.web.servlet;

import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yx1996.domain.Product;
import com.yx1996.service.ProductService;

/**
 * Servlet implementation class ProductInFoServlet
 */
public class ProductInFoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProductInFoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String pid = request.getParameter("pid");
		String cid = request.getParameter("cid");
		String currentPage = request.getParameter("currentPage");
		ProductService productService = new ProductService();
		Product productInFo = productService.findProduct(pid);
		request.setAttribute("productInFo", productInFo);
		request.setAttribute("cid", cid);
		
		
		String pids = pid;
		request.setAttribute("currentPage", currentPage);
		Cookie[] cookies = request.getCookies();
		for(Cookie cookie:cookies){
			if("pids".equals(cookie.getName())){
				pids = cookie.getValue();
				String[] split = pids.split("-");
				List<String> asList = Arrays.asList(split);
				LinkedList<String> pids_linked = new LinkedList<String>(asList);
				if(pids_linked.contains(pid)){
					pids_linked.remove(pid);
				}
				pids_linked.addFirst(pid);
				StringBuffer pids_buf = new StringBuffer();
				for(int i=0;i<pids_linked.size()&&i<7;i++){
					pids_buf.append(pids_linked.get(i));
					pids_buf.append("-");
				}
				pids = pids_buf.substring(0,pids_buf.length()-1);
			}
		}
		Cookie cookie = new Cookie("pids", pids);
		response.addCookie(cookie);
		request.getRequestDispatcher("product_info.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
